<template>
  <!-- 告警记录管理 -->
  <div class="filterContent">
    <a-form :model="filterForm" layout="inline">
      <a-form-item label="电站">
        <a-select
          v-model:value="filterForm.stationId"
          class="formSelect"
          placeholder="请选择"
          show-search
          optionFilterProp="label"
          @change="changeStation"
          style="width: 150px"
          allow-clear
        >
          <a-select-option
            v-for="item in stationNameOptions"
            :key="item.stationId"
            :value="item.stationId"
            :label="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="电池堆">
        <a-select
          ref="select"
          v-model:value="filterForm.linkId"
          class="formSelect"
          placeholder="请选择"
          :disabled="!filterForm.stationId"
          @change="changeLink"
          allow-clear
          style="width: 120px"
        >
          <a-select-option
            v-for="item in linkList"
            :key="item.deviceId"
            :value="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电池簇">
        <a-select
          ref="select"
          v-model:value="filterForm.blockId"
          class="formSelect"
          placeholder="请选择"
          :disabled="!filterForm.linkId"
          allow-clear
          style="width: 120px"
        >
          <a-select-option
            v-for="item in blockList"
            :key="item.deviceId"
            :value="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="pack">
        <a-select
          ref="select"
          v-model:value="filterForm.packNumber"
          class="formSelect"
          placeholder="请选择"
          :disabled="!filterForm.stationId"
          allow-clear
          style="width: 120px"
        >
          <a-select-option v-for="n in packNumber" :key="n" :value="n">
            {{ n }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电芯">
        <a-select
          ref="select"
          v-model:value="filterForm.batteryNumber"
          class="formSelect"
          placeholder="请选择"
          :disabled="!filterForm.stationId"
          allow-clear
          style="width: 120px"
        >
          <a-select-option v-for="n in cellNumber" :key="n" :value="n">
            {{ n }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="告警状态">
        <a-select
          ref="select"
          v-model:value="filterForm.evtStatus"
          class="formSelect"
          placeholder="请选择"
          allow-clear
          style="width: 120px"
        >
          <a-select-option
            v-for="item in WARN_CONFIRM_STATUS"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="告警状态类别">
        <a-select
          ref="select"
          v-model:value="filterForm.warnType"
          class="formSelect"
          placeholder="请选择"
          style="width: 120px"
          allow-clear
          show-search
          :filter-option="filterOption"
          optionFilterProp="label"
        >
          <a-select-option
            v-for="item in listWarnName"
            :value="item.val"
            :key="item.val"
            :label="item.title"
          >
            {{ item.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="告警等级">
        <a-select
          ref="select"
          v-model:value="filterForm.warnLevel"
          class="formSelect"
          placeholder="请选择"
          style="width: 170px"
          allow-clear
        >
          <a-select-option
            v-for="item in WARN_LEVEL_LIST"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-button type="primary" class="filterBtn" @click="searchData"
        >查询</a-button
      >
    </a-form>
  </div>
  <a-button
    type="primary"
    v-if="subDatas.length > 0"
    style="margin-bottom: 5px"
    @click="batchConfirm"
    >批量确认</a-button
  >
  <div class="tableContent" ref="tableContainerRef">
    <!-- subDatas -->

    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      @resizeColumn="handleResizeColumn"
      :pagination="false"
      :loading="tableLoading"
      :scroll="tableScroll"
      class="custom-table"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <template #bodyCell="{ column, record }">
        <!-- <template v-if="column.key === 'warnLevel'">
          <span style="color: red">
            {{ WARN_LEVEL[record.status] }}
          </span>
        </template> -->

        <template v-if="column.key === 'evtStatus'">
          {{ record.evtStatus === 1 ? "确认" : "未确认" }}
        </template>
        <template v-if="column.key === 'warnLevel'">
          <div :class="record.warnLevel === 3 ? 'redCircle' : ''">
            {{ WARN_LEVEL[record.warnLevel] }}
          </div>
        </template>
        <template v-if="column.key === 'pdValue'">
          <a-tooltip placement="topLeft">
            <template #title>{{ record.pdValue }}</template>
            {{ record.pdValue }}
          </a-tooltip>
        </template>
        <template v-if="column.key === 'handle'">
          <a-button type="link" @click="handleConfirm(record)"
            >确认告警</a-button
          >
          <a-button type="link" disabled>发起工单</a-button>
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="filterForm.current"
      v-model:page-size="filterForm.size"
      :total="total"
      position="bottomRight"
      show-size-changer
      @change="getWarnInfoList"
      :show-total="(total) => `总共 ${total} 条`"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>
  </div>

  <ConfirmWarn
    :confirmWarnVisible="confirmWarnVisible"
    :id="confirmId"
    :rowData="rowData"
    @update:confirmWarnVisible="confirmWarnVisible = $event"
    @update:getWarnInfoList="getWarnInfoList"
  />
</template>
<script setup>
import {
  RULE_TYPE_LIST,
  WARN_LEVEL_LIST,
  WARN_EQUIP_LEVEL_LIST,
  WARN_LEVEL,
  WARN_CONFIRM_STATUS,
} from "@/constants/stationConfig.js"
import AddRule from "@/views/EventView/AlarmManage/AlarmRule/addRule.vue"
import StatusConfig from "@/views/EventView/AlarmManage/AlarmRule/statusConfig.vue"
import ConfirmWarn from "@/views/EventView/AlarmManage/AlarmLog/confirmWarn.vue"

import useTableScroll from "@/hooks/useTableScroll"
import { formatMillisecondsToDHM } from "@/utils/common"
const route = useRoute()
const $api = inject("$api")

const filterForm = ref({
  stationId: null,
  warnLevel: null,
  linkId: null,
  blockId: null,
  ruleName: null,
  packNumber: null,
  batteryNumber: null,
  evtStatus: 0,
  size: 10,
  current: 1,
})
const total = ref()
const confirmWarnVisible = ref(false)
const confirmId = ref(0)

const tableData = ref([])
const isEdit = ref(false)
const rowData = ref({})
const tableLoading = ref(false)
const columns = ref([
  {
    title: "电站",
    dataIndex: "stationName",
    key: "stationName",
    width: 120,
    align: "center",
    fixed: "left",
  },
  {
    title: "告警信息",
    dataIndex: "warnMessage",
    key: "warnMessage",
    width: 200,
    align: "center",
  },
  {
    title: "告警开始时间",
    dataIndex: "startTime",
    key: "startTime",
    width: 160,
    align: "center",
  },
  {
    title: "告警规则备注",
    dataIndex: "comment",
    key: "comment",
    width: 200,
    align: "center",
  },
  {
    title: "告警等级",
    dataIndex: "warnLevel",
    key: "warnLevel",
    width: 200,
    align: "center",
  },

  {
    title: "电池堆",
    dataIndex: "linkName",
    key: "linkName",
    width: 180,
    align: "center",
  },

  {
    title: "电池簇",
    dataIndex: "blockName",
    key: "blockName",
    width: 160,
    align: "center",
  },
  {
    title: "pack",
    dataIndex: "packNumber",
    key: "packNumber",
    width: 180,
    align: "center",
  },
  {
    title: "电芯",
    dataIndex: "batteryNumber",
    key: "batteryNumber",
    width: 180,
    align: "center",
  },
  {
    title: "运维建议",
    dataIndex: "maintenanceAdvice",
    key: "maintenanceAdvice",
    width: 200,
    align: "center",
  },
  {
    title: "告警规则",
    dataIndex: "ruleName",
    key: "ruleName",
    width: 180,
    align: "center",
  },
  /* {
    title: "告警结束时间",
    dataIndex: "endTime",
    key: "endTime",
    width: 160,
    align: "center",
  },
  {
    title: "告警持续时长",
    dataIndex: "offTime",
    key: "offTime",
    width: 160,
    align: "center",
  }, */
  {
    title: "告警确认时间",
    dataIndex: "confirmTime",
    key: "confirmTime",
    width: 160,
    align: "center",
  },
  {
    title: "状态分类",
    dataIndex: "warnTypeStr",
    key: "warnTypeStr",
    width: 150,
    align: "center",
  },
  {
    title: "告警状态",
    dataIndex: "evtStatus",
    key: "evtStatus",
    width: 150,
    align: "center",
  },
  {
    title: "确认内容",
    dataIndex: "confirmMessage",
    key: "confirmMessage",
    width: 160,
    align: "center",
  },
  {
    title: "参数名称",
    dataIndex: "attrName",
    key: "attrName",
    width: 160,
    align: "center",
  },
  {
    title: "实时pdData值",
    dataIndex: "pdValue",
    key: "pdValue",
    width: 160,
    align: "center",
    customCell: (record) => ({
      style: {
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
        maxWidth: "160px",
      },
    }),
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 160,
    align: "center",
    fixed: "right",
  },
])
onMounted(async () => {
  await handleSearchStationName()
  await getListWarnType()
  if (Object.keys(route.query).length > 0 && route.query?.stationId !== null) {
    filterForm.value.stationId = Number(route.query.stationId)
    filterForm.value.evtStatus = 0
    if (Object.keys(route.query).length > 0 && route.query?.warnType) {
      filterForm.value.warnType = listWarnName.value.find(
        (item) => item.title === route.query.warnType
      )?.val
    }
  }

  getWarnInfoList()
})

const listWarnName = ref([])
const getListWarnType = async () => {
  const res = await $api.listWarnType()
  if (res && res.code === 0) {
    const flattenMenuList = (menuList) => {
      let result = []
      menuList.forEach((menu) => {
        if (menu.children && menu.children.length > 0) {
          result = result.concat(flattenMenuList(menu.children))
        } else {
          result.push(menu)
        }
      })
      return result
    }
    listWarnName.value = flattenMenuList(res.data)
  }
}
function handleResizeColumn(w, col) {
  col.width = w
}

function handleConfirm(record) {
  confirmWarnVisible.value = true
  confirmId.value = record?.id
}
const stationNameOptions = ref([])
const handleSearchStationName = async () => {
  const res = await $api.companyStationtList()
  stationNameOptions.value = res.data.filter(
    (item) => item.isChargeProject === 0
  )
  await nextTick()
}

// watch(
//   () => filterForm.value.stationId, // 提供一个 getter 函数来获取要监听的值
//   async (newValue, oldValue) => {
//     if (newValue !== null) {
//       const params = {
//         stationId: newValue,
//       }
//       try {
//         const res = await $api.getDeviceTreeByStationId(params)
//         linkDeviceTreeOptions.value = res.data.linkDataList
//         linkIdToBlockDataMap.value = {}
//         packNumber.value = 0
//         cellNumber.value = 0
//         const linkIdToBlockData = {}
//         res.data.linkDataList.forEach((link) => {
//           if (link.linkId && Array.isArray(link.blockDataList)) {
//             linkIdToBlockData[link.linkId] = link.blockDataList
//           }
//         })
//         linkIdToBlockDataMap.value = linkIdToBlockData
//         packNumber.value = res.data.packNumber
//         cellNumber.value = res.data.cellNumber
//       } catch (error) {
//         console.error("Error fetching device tree:", error)
//         // 处理错误，例如显示错误消息或重置 linkDeviceTreeOptions
//       }
//     }
//   }
// )
const packNumber = ref(0)
const cellNumber = ref(0)
const getDeviceTree = (id) => {
  if (id) {
    const params = {
      stationId: id,
    }
    $api.getDeviceTreeByStationId(params).then((res) => {
      packNumber.value = res.data.packNumber
      cellNumber.value = res.data.cellNumber
    })
  }
}
//获取电池堆
let linkList = ref([])
let blockList = ref([])
const changeStation = async (id) => {
  //filterForm.value.stationId = id
  filterForm.value.linkId = null
  filterForm.value.blockId = null
  filterForm.value.packNumber = null
  linkList.value = []
  blockList.value = []
  getLinkList(id)
  getDeviceTree(id)
}
const getLinkList = async (id) => {
  const params = { stationId: id }
  const res = await $api.energyLinkList(params)
  if (res && res.code === 0) {
    linkList.value = res.data
  }
}
//获取电池簇
const changeLink = async (id) => {
  filterForm.value.blockId = null
  filterForm.value.packNumber = null
  blockList.value = []
  getBlockList(id)
}
const getBlockList = async (id) => {
  const { stationId } = filterForm.value
  const params = { stationId: stationId, linkId: id }
  const res = await $api.powerBlockList(params)
  if (res && res.code === 0) {
    blockList.value = res.data
  }
}

// 构建映射对象
// function buildLinkIdToBlockDataMap(response) {
//   const linkIdToBlockData = {}

//   if (response && response.data && Array.isArray(response.data.linkDataList)) {
//     response.data.linkDataList.forEach((link) => {
//       if (link.linkId && Array.isArray(link.blockDataList)) {
//         linkIdToBlockData[link.linkId] = link.blockDataList
//       }
//     })
//   }

//   return linkIdToBlockData
// }

// 使用函数生成映射对象

const linkNameOptions = ref([])

const handleSearchLinkName = async (linkName) => {
  const params = {
    linkName: linkName,
    stationId: filterForm.value.stationId,
  }
  const res = await $api.fuzzyQueryLink(params)
  linkNameOptions.value = res.data.map((item) => ({
    value: item.stationName,
  }))
}

const blockNameOptions = ref([])

const handleSearchBlockName = async (blockName) => {
  const params = {
    blockName: blockName,
    linkId: filterForm.value.linkId,
  }
  const res = await $api.fuzzyQueryBlock(params)
  blockNameOptions.value = res.data.map((item) => ({
    value: item.stationName,
  }))
}
const searchData = () => {
  filterForm.value.current = 1
  getWarnInfoList()
}
const getWarnInfoList = async () => {
  //const { current, size, ...rest } = filterForm.value
  tableLoading.value = true
  const res = await $api.warnInfoPage(filterForm.value)
  if (res && res.code === 0) {
    tableData.value = res.data.records.map((item, index) => ({
      ...item,
      key: item.id,
      index: index + 1,
      offTime: item.hasOwnProperty("warnDuration")
        ? formatMillisecondsToDHM(item.warnDuration)
        : "--",
    }))
    total.value = res.data.total
  }
  tableLoading.value = false
}
const tableContainerRef = ref(null)
const { tableScroll } = useTableScroll(tableData, tableContainerRef, 120)
const selectedRowKeys = ref([])
const subDatas = ref([])
const onSelectChange = (selectedKeys, selectedRows) => {
  selectedRowKeys.value = selectedKeys
  subDatas.value = selectedRows.map((row) => row.id)
  /* console.log(
    "选中的数据id:",
    selectedRows.map((row) => row.id)
  ) */
}
//批量确认
const batchConfirm = async () => {
  const res = await $api.warnConfirmBatch(subDatas.value)
  if (res && res.code === 0) {
    message.success("确认成功")
    subDatas.value = []
    getWarnInfoList()
  }
}
</script>

<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.redCircle {
  color: red;
}
.formInput {
  width: 155px;
}
.filterBtn {
  margin: 0 20px 20px 0;
  &:last-child {
    margin-right: 0;
  }
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
</style>
